package com.cloudpark.mqtt;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;

import com.cloudpark.common.util.Constants;

public class MQTTSubListenter implements ServletContextListener {

	private static final Logger log = Logger.getLogger(MQTTSubListenter.class);
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		try {

            // 创建MqttClient
            MqttClient client = new MqttClient(Constants.MQTT_ADDRESS, Constants.MQTT_SUBSCRIBE);

            // 回调处理类
            CallBack callback = new CallBack();
            client.setCallback(callback);

            // 创建连接可选项信息
            MqttConnectOptions conOptions = new MqttConnectOptions();
            conOptions.setCleanSession(Constants.MQTT_CLEANSESSION);
            conOptions.setKeepAliveInterval(Constants.MQTT_KEEPALIVEINTERVAL);

            // 连接broker
            client.connect(conOptions);

            // 发布相关的订阅
            if (Constants.MQTT_TEST_ENV) {
            	client.subscribe(Constants.MQTT_TOPIC_SERVER, Constants.MQTT_QoS);
            } else {
             client.unsubscribe(Constants.MQTT_TOPIC_SERVER);
            	client.subscribe(Constants.MQTT_TOPIC_CLIENT, Constants.MQTT_QoS);
            }

        } catch (Exception e) {
            log.error("mqtt订单监听器初始化......", e);
        }
	}

}
